import requests
import json
import browsercookie
import openpyxl
from datetime import datetime
import threading
import time

try:
   import queue
except ImportError:
   import Queue as queue

# 获取已登录的微信管理后台cookie，调用已发送文章列表api，获取微信公众号文章阅读数、点赞数、赞赏数等信息。

token=32464339
api_sent_list='https://mp.weixin.qq.com/cgi-bin/newmasssendpage?count={limit}&begin={offset}&lang=zh_CN&token={token}&lang=zh_CN&f=json&ajax=1'

current_time=datetime.now().strftime("%Y%m%d-%H%M%S")
file_name="wx-summary-{cur_str}.xlsx".format(cur_str=current_time)

queue_topic_quit="quit"

queue_topic_article="article"

queue_topic="topic"
queue_results="results"

request_header_agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4122.7 Safari/537.36"

def get_article_list(offset=0, limit=100):
    """ 获取已发送文章列表
    """
    print("article_list offset={0}, limit={1}".format(offset, limit))

    login_header = {
        "User-Agent": request_header_agent
    }
    url = api_sent_list.format(token=token, offset=offset, limit=limit)
    responseRes = requests.get(url, headers=login_header, verify=False, cookies=browsercookie.chrome())
    print(url)
    print(f"statusCode = {responseRes.status_code}")
    # print(f"text = {responseRes.text}")
    return responseRes.json()


def write_workbook(file, item_list):
    wb = openpyxl.Workbook(write_only=True) 
    sheet = wb.create_sheet() 

    for row in item_list:
        sheet.append(row)
    
    wb.save(file)

def format(timestamp):
    return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')


def process_article(_queue):
    """分页获取文章列表并push文章消息到消费队列
    """
    _page=0

    #bug of weixin, only can be 7.
    _limit=7

    # titile 
    _queue.put({
        queue_topic: queue_topic_article,
        queue_results: ["文章名称","发布时间","阅读数","点赞数","在看数", "留言数","赞赏数"]
    })

    # 分页获取文章列表
    while True:
        raw_article_list=get_article_list(offset=_page*_limit, limit=_limit)
        _article_total_count = raw_article_list['total_count']
        print('total article count:', _article_total_count)
        if _article_total_count <= 0:
            print('total article count <= 0, quit')
            break
        
        appmsg_list = raw_article_list.get('sent_list')

        if not appmsg_list:
            print('no more article, quit.')
            break

        for appmsg in appmsg_list:
            if not appmsg.get('appmsg_info'):
                print('ignore empty appmsg_info.')
                continue

            appmsg_info = appmsg.get('appmsg_info')[0]
            sent_info = appmsg.get('sent_info')
            # push article message to Queue
            _queue.put({
                queue_topic: queue_topic_article, 
                queue_results: [appmsg_info['title'], format(sent_info['time']), appmsg_info.get('read_num'), appmsg_info.get('old_like_num'), appmsg_info.get('like_num'), appmsg_info.get('comment_num'), appmsg_info.get('reward_money')]
            })
        # 下一页
        _page=_page+1


class Consumer(threading.Thread):
    """消费线程-保存明细"""
    def __init__(self, queue):
        super(Consumer, self).__init__()
        self._queue = queue

    def run(self):
        print('Reward Consumer Starting!')
        count=0
        wb = openpyxl.Workbook() 
        sheet = wb.create_sheet(title = "info") 
        while True:
            _content = self._queue.get()
            print(_content)
            # quit
            if isinstance(_content, str) and _content == queue_topic_quit:
                break

            # quit
            if isinstance(_content, dict) and _content.get(queue_topic) == queue_topic_quit:
                break

            # 保存明细
            if isinstance(_content, dict) and _content.get(queue_topic) == queue_topic_article:        
                sheet.append(_content.get(queue_results))
                count=count+1
                wb.save(file_name)
                continue

        print('Consumer End!')


class Producter(threading.Thread):
    """生产者线程"""
    def __init__(self, queue):
        super(Producter, self).__init__()
        self._queue = queue

    def run(self):
        process_article(_queue)
        print('put queue done')

if __name__ == '__main__':
    _start_time = time.time()
    _queue = queue.Queue()
    pt = Producter(_queue)
    _worker = Consumer(_queue)

    pt.start()
    _worker.start()

    pt.join()

    _queue.put({queue_topic:queue_topic_quit})

    _worker.join()

    _t = time.time() - _start_time
    print(f"Done! Time taken: {_t}")